//
//  HaiTaoVC.m
//  MyTest
//
//  Created by zhiyou on 16-4-12.
//  Copyright (c) 2016年 wangyang. All rights reserved.
//

#import "HaiTaoVC.h"
#import "LoginVC.h"
#import "TotalVC.h"
#import "ClassVC.h"
#import "JinRiVC.h"
#import "Recommond.h"
#import "DaiGouCell.h"
#import "JingXuanCell.h"
#import "TuiJanCell.h"
#import "WebVC.h"
#define BASE_URL @"http://www.shihuo.cn/app/haitaoIndex?platform=ios&timestamp=1460374823&v=4.0.2&token=623b9f3b7deec35d54f9446a29f8bdf9"
@interface HaiTaoVC () <UITableViewDataSource, UITableViewDelegate,UIScrollViewDelegate>
{
    UIScrollView    *_scrollView;
    UIPageControl   *_pageControl;
    NSTimer         *_timer;
}
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *bannerArr;
@property (nonatomic, strong) NSMutableArray *hotArr;
@property (nonatomic, strong) NSMutableArray *jingxuanArr;
@property (nonatomic, strong) NSMutableArray *recommondArr;
@property (nonatomic, strong) NSArray *urlArr;
@property (nonatomic, strong) NSArray *URLArr;
@end

@implementation HaiTaoVC
- (void)viewWillAppear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden = NO;
    self.navigationController.navigationBarHidden = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.title = @"识货海淘";
    [self rightBarButton];
    _bannerArr = [[NSMutableArray alloc] init];
    _hotArr = [[NSMutableArray alloc] init];
    _jingxuanArr = [[NSMutableArray alloc] init];
    _recommondArr = [[NSMutableArray alloc] init];
    _urlArr = @[@"http://m.shihuo.cn/special/index?id=770",@"http://m.shihuo.cn/special/index?id=774",@"http://m.shihuo.cn/special/index?id=758",@"http://m.shihuo.cn/special/index?id=785",@"http://m.shihuo.cn/special/index?id=725"];
    _URLArr = @[@"http://m.shihuo.cn/xianhuo",@"http://m.shihuo.cn/special/index?id=781",@"http://m.shihuo.cn/special/index?id=596",@"http://m.shihuo.cn/special/index?id=747"];
    [self setThread];
    
}
- (void)setThread
{
    NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(refresh1) object:nil];
    [thread start];
}
- (void)refresh1
{
    [self getData];
    [self performSelectorOnMainThread:@selector(refreshUI) withObject:nil waitUntilDone:NO];
}
- (void)refreshUI
{
    [_tableView reloadData];
}
#pragma mark -- UITableViewDataSource, UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0 || section == 1) {
        if (_hotArr.count==0) {//zhuyi
            return 0;
        }
        return 1;
    }else {
        return _recommondArr.count;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        DaiGouCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DaiGouCell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        NSMutableArray *arr = [[NSMutableArray alloc] init];
        for (Banner *banner in _hotArr)
        {
            [arr addObject:banner.img_url];
        }
        
        [cell.imgView1 sd_setImageWithURL:[NSURL URLWithString:arr[0]]];
        [cell.imgView2 sd_setImageWithURL:[NSURL URLWithString:arr[1]]];
        [cell.imgView3 sd_setImageWithURL:[NSURL URLWithString:arr[2]]];
        [cell.imgView4 sd_setImageWithURL:[NSURL URLWithString:arr[3]]];
        [cell.imgView5 sd_setImageWithURL:[NSURL URLWithString:arr[4]]];
        UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(daiGou:)];
        tap1.numberOfTapsRequired = 1;
        [cell.imgView1 addGestureRecognizer:tap1];
        UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(daiGou:)];
        tap2.numberOfTapsRequired = 1;
        [cell.imgView2 addGestureRecognizer:tap2];
        UITapGestureRecognizer *tap3 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(daiGou:)];
        tap3.numberOfTapsRequired = 1;
        [cell.imgView3 addGestureRecognizer:tap3];
        UITapGestureRecognizer *tap4 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(daiGou:)];
        tap4.numberOfTapsRequired = 1;
        [cell.imgView4 addGestureRecognizer:tap4];
        UITapGestureRecognizer *tap5 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(daiGou:)];
        tap5.numberOfTapsRequired = 1;
        [cell.imgView5 addGestureRecognizer:tap5];
        
        return cell;
    }else  if(indexPath.section == 1) {
        JingXuanCell *cell = [tableView dequeueReusableCellWithIdentifier:@"JingXuanCell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        NSMutableArray *arr = [[NSMutableArray alloc] init];
        for (Banner *banner in _jingxuanArr)
        {
            [arr addObject:banner.img_url];
        }
        
        [cell.imgView1 sd_setImageWithURL:[NSURL URLWithString:arr[0]]];
        [cell.imgView2 sd_setImageWithURL:[NSURL URLWithString:arr[1]]];
        [cell.imgView3 sd_setImageWithURL:[NSURL URLWithString:arr[2]]];
        [cell.imgView4 sd_setImageWithURL:[NSURL URLWithString:arr[3]]];
        
        UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(jingXuan:)];
        tap1.numberOfTapsRequired = 1;
        [cell.imgView1 addGestureRecognizer:tap1];
        UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(jingXuan:)];
        tap2.numberOfTapsRequired = 1;
        [cell.imgView2 addGestureRecognizer:tap2];
        UITapGestureRecognizer *tap3 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(jingXuan:)];
        tap3.numberOfTapsRequired = 1;
        [cell.imgView3 addGestureRecognizer:tap3];
        UITapGestureRecognizer *tap4 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(jingXuan:)];
        tap4.numberOfTapsRequired = 1;
        [cell.imgView4 addGestureRecognizer:tap4];
        
        return cell;
    }else {
        TuiJanCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TuiJanCell" forIndexPath:indexPath];
        Recommond *recommond = _recommondArr[indexPath.row];
        [cell.imgView sd_setImageWithURL:[NSURL URLWithString:recommond.pic]];
        cell.titleLabel.text = recommond.title;
        cell.priceLabel.text = [NSString stringWithFormat:@"到手价  %@",recommond.price];
        cell.sourceLabel.text = [NSString stringWithFormat:@"商家:  %@",recommond.shop_type];
        return cell;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 200;
    }else if(indexPath.section == 1) {
        return 250;
    } else {
        return 100;
    }
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (section == 2) {
        return @"精品推荐";
    }else {
        return nil;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0 || section == 1) {
        return 5;
    }else {
        return 20;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 5;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (void)daiGou:(UIGestureRecognizer *)tap
{
    UIImageView *imgView = (UIImageView *)[tap view];
    WebVC *vc = [[WebVC alloc] init];
    vc.urlStr = _urlArr[imgView.tag-100];
    [self.navigationController pushViewController:vc animated:YES];
    
}
- (void)jingXuan:(UIGestureRecognizer *)tap
{
    UIImageView *imgView = (UIImageView *)[tap view];
    WebVC *vc = [[WebVC alloc] init];
    vc.urlStr = _URLArr[imgView.tag-1000];
    [self.navigationController pushViewController:vc animated:YES];
}
#pragma mark -- 创建tableHeaderView
- (UIView *)headerView
{
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, Width, Height/4+60)];
    [self scrollView];
    [headerView addSubview:_scrollView];
    [headerView addSubview:_pageControl];
    headerView.backgroundColor = [UIColor whiteColor];
    
    NSArray *arr = @[@"all",@"pageSearch",@"sale"];
    for (int i = 0; i < arr.count; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake((Width/3+10)*i+10, Height/4+10, Width/3-30, 40);
        button.tag = 100+i;
        [button setBackgroundImage:[UIImage imageNamed:arr[i]] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(clickBtn:) forControlEvents:UIControlEventTouchUpInside];
        [headerView addSubview:button];
    }
    return headerView;
}
- (void)clickBtn:(UIButton *)button
{
    UIViewController *vc = nil;
    switch (button.tag) {
        case 100:
            vc = [[TotalVC alloc] init];
            break;
        case 101:
            vc = [[ClassVC alloc] init];
            break;
        case 102:
            vc = [[JinRiVC alloc] init];
            vc.title = @"海淘优惠";
            break;
        default:
            break;
    }
    [self.navigationController pushViewController:vc animated:YES];
}
#pragma mark -- 创建滚动视图
- (void)scrollView
{
    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, Width, Height/4)];
    for (int i = 0; i < _bannerArr.count; i++) {
        
        // 图片坐标从0开始
        UIImageView * imageView=  [[UIImageView alloc] initWithFrame:CGRectMake(Width*i, 0, Width, Height/4)];
        Banner *banner = _bannerArr[i];
        NSString *urlStr = [NSString stringWithFormat:@"%@",banner.img_url];
        NSURL *url = [NSURL URLWithString:urlStr];
        NSData *data = [NSData dataWithContentsOfURL:url];
        UIImage *image = [UIImage imageWithData:data];
        imageView.image = image;
        [_scrollView addSubview:imageView];
    }
    _scrollView.contentSize = CGSizeMake(Width * _bannerArr.count, 120);
    _scrollView.pagingEnabled = YES;
    _scrollView.showsHorizontalScrollIndicator = NO;
    _scrollView.showsVerticalScrollIndicator = NO;
    _scrollView.indicatorStyle = UIScrollViewIndicatorStyleWhite;
    _scrollView.delegate = self;
    
    
    _pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(0, Height/4-20, Width, 20)];
    
    _pageControl.numberOfPages = _bannerArr.count;
    _pageControl.pageIndicatorTintColor = [UIColor whiteColor];
    _pageControl.currentPageIndicatorTintColor = [UIColor redColor];
    [_pageControl addTarget:self action:@selector(pageControlChanged) forControlEvents:UIControlEventValueChanged];
    
    _timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(changeImage) userInfo:nil repeats:YES];
}

- (void)pageControlChanged
{
    [_scrollView setContentOffset:CGPointMake(_pageControl.currentPage *Width, 0) animated:YES];
    [_timer invalidate];
    _timer = nil;
}

- (void)changeImage
{
    // 定义一个静态变量,代表方向
    static int direction = 1;
    if (_scrollView.contentOffset.x == 0)
    {
        direction = 1;
    }
    if (_scrollView.contentOffset.x == Width*(_bannerArr.count-1))
    {
        direction = -1;
    }
    // 设置滚动视图的偏移量,带动画
    [_scrollView setContentOffset:CGPointMake(_scrollView.contentOffset.x+Width*direction, 0) animated:YES];
}
#pragma mark -- UIScrollViewDelegate
// 将要开始拖拽
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    // 开始拖拽时,把定时器关闭
    [_timer invalidate];
    _timer = nil;
}
//已经结束拖拽
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{

}
// 将要开始减速
- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView
{
    
}
// 已经结束减速
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    float offSet_x = scrollView.contentOffset.x;
    _pageControl.currentPage = offSet_x/Width;
    // 结束减速把定时器重新开启
    if (_timer == nil) {
        _timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(changeImage) userInfo:nil repeats:YES];
    }
}
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
{
    if (_timer == nil)
    {
        _timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(changeImage) userInfo:nil repeats:YES];
    }
    
    float offSet_x = scrollView.contentOffset.x;
    _pageControl.currentPage = offSet_x/Width;
}
#pragma mark -- 创建右按钮
- (void)rightBarButton
{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setBackgroundImage:[UIImage imageNamed:@"shopping"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(goShoppingCart) forControlEvents:UIControlEventTouchUpInside];
    button.frame = CGRectMake(0, 0, 40, 30);

    UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithCustomView:button];
    self.navigationItem.rightBarButtonItem = rightButton;
}
- (void)goShoppingCart
{
    LoginVC *vc = [[LoginVC alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}
#pragma mark -- 获取请求数据
- (void)getData
{
    _bannerArr = [[NSMutableArray alloc] init];
    _hotArr = [[NSMutableArray alloc] init];
    _jingxuanArr = [[NSMutableArray alloc] init];
    _recommondArr = [[NSMutableArray alloc] init];
    [MyRequest getWithURL:BASE_URL parameters:nil success:^(NSDictionary *dic) {
        NSDictionary *dictionary = [dic objectForKey:@"data"];
        NSArray *bannerArr = [dictionary objectForKey:@"banner"];
        
        self.bannerArr = [MyTools getBannerWithArray:bannerArr];
        
        NSArray *hotArr = [dictionary objectForKey:@"hot"];
        self.hotArr = [MyTools getBannerWithArray:hotArr];
        
        NSArray *jingxuanArr = [dictionary objectForKey:@"jingxuan"];
        self.jingxuanArr = [MyTools getBannerWithArray:jingxuanArr];
        
        NSArray *recommondArr = [dictionary objectForKey:@"recommend"];
        self.recommondArr = [MyTools getRecommondWithArray:recommondArr];
        
        [self.view addSubview:self.tableView];
        
    } fail:^(NSError *error) {
        NSLog(@"%@",error);
    }];
}


- (void)refresh
{
    __block HaiTaoVC *mySelf = self;
    
    [_tableView addPullToRefreshWithActionHandler:^{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [mySelf.tableView.pullToRefreshView stopAnimating];
            [mySelf getData];
        });
    }];
    
}
#pragma mark -- 创建表
- (UITableView *)tableView
{
    if (_tableView == nil) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, Width, Height-64-49) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
        [_tableView registerClass:[DaiGouCell class] forCellReuseIdentifier:@"DaiGouCell"];
        [_tableView registerClass:[JingXuanCell class] forCellReuseIdentifier:@"JingXuanCell"];
        [_tableView registerClass:[TuiJanCell class] forCellReuseIdentifier:@"TuiJanCell"];
        self.tableView.tableHeaderView = [self headerView];
    }
    [self refresh];
    return _tableView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
